<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="100px" @submit.native.prevent>
      <el-form-item label="管理员账号" prop="username">
        <el-input v-model="pram.username" placeholder="管理员账号" />
      </el-form-item>
      <el-form-item label="管理员密码" prop="password">
        <el-input
          v-model="pram.password"
          placeholder="管理员密码"
          clearable
          @input="handlerPwdInput"
          @clear="handlerPwdInput"
        />
      </el-form-item>
      <el-form-item v-if="pram.password" label="确认密码" prop="repwd">
        <el-input v-model="pram.repwd" placeholder="确认密码" clearable />
      </el-form-item>
      <el-form-item label="管理员姓名" prop="realName">
        <el-input v-model="pram.realName" placeholder="管理员姓名" />
      </el-form-item>
      <el-form-item label="管理员身份" prop="roles">
        <el-select v-model="pram.roles" placeholder="身份" clearable style="width: 100%">
          <el-option
            v-for="(item,index) in roleList.list"
            :key="index"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="管理员村组" prop="village" v-if="pram.roles!==1">
        <el-cascader style="width: 100%"
          v-model="pram.villageId"
          :options="villageList"
          :props="optionProps"
          @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model.number="pram.phone" type="number" placeholder="联系电话" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="pram.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')" v-hasPermi="['admin:system:admin:update','admin:system:admin:save']">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as roleApi from '@/api/role.js'
import * as systemAdminApi from '@/api/systemadmin.js'
import {selectTreeApi} from '@/api/systemadmin.js'
import {Debounce} from '@/utils/validate'
import * as selfUtil from "@/utils/ZBKJIutil";
export default {
  // name: "edit"
  components: { },
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return { rules: [] }
      }
    },
    allRoleList: {
      type: Object
    },
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请填写手机号'));
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确!'));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pram.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      constants:this.$constants,
      pram: {
        username: null,
        password: null,
        repwd: null,
        realName: null,
        roles: null, //不能为0，必须为null
        status: 1,
        phone: null,
        id: null,
        villageId:[]
      },
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
      },
      roleList: {},
      villageList:[],
      rules: {
        username: [{ required: true, message: '请填管理员账号', trigger: ['blur', 'change'] }],
        password: [{ required: true, message: '请填管理员密码', trigger: ['blur', 'change'] }],
        repwd: [{ required: true, message: '确认密码密码', validator: validatePass, trigger: ['blur', 'change'] }],
        realName: [{ required: true, message: '管理员姓名', trigger: ['blur', 'change'] }],
        roles: [{ required: true, message: '管理员身份', trigger: ['blur', 'change'] }],
        villageId: [{ required: true, message: '管理员村组', trigger: ['blur', 'change'] }],
        //phone: [{ required: true, message: '请填正确的联系电话',  validator: validatePhone, trigger: ['blur', 'change'] }],
      },
      departmentList:[]
    }
  },
  mounted() {
    this.initEditData()
    this.selectTreeList()
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },
    handleChange(value) {
      this.pram.villageId=value
    },
    initEditData() {
      this.roleList = this.allRoleList

      if (this.isCreate !== 1) return //编辑
      const { username, realName, roles, phone, status, id,villageId } = this.editData //通过list中slot-scope=“scope“，scope.$index就是该行的下标，scope.row就是该行的数据所有消息对象，有了这两个参数就可以实现编辑、删除功能（this.editData就是scope.row传入的对象参数）
      this.pram.username = username
      this.pram.realName = realName
      this.pram.phone = phone
      /*const _roles = []
      if (roles.length > 0 && !roles.includes(',')) {
        //如果权限id集合有长度并且是只有一个，就将它Push进_roles这个数组
        _roles.push(Number.parseInt(roles))
      } else {
        //否则就将多个id集合解构以后push进roles并且转换为整型
        _roles.push(...roles.split(',').map(item => Number.parseInt(item)))
      }*/
      this.pram.roles = roles
      this.pram.status = status
      this.pram.id = id
      this.pram.phone = phone
      this.rules.password = []
      this.rules.repwd = []
      this.pram.villageId=villageId
    },
    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        if (this.isCreate === 0) {
          this.handlerSave()
        } else {
          this.handlerEdit()
        }
      })
    }),
    handlerSave() {
      //console.log(this.pram);return;
      let pram=JSON.parse(JSON.stringify(this.pram));
      pram.villageId=pram.villageId[2]
      systemAdminApi.adminAdd(pram).then(data => {
        this.$message.success('创建管理员成功')
        this.$emit('hideEditDialog')
      })
    },
    selectTreeList() {
      selectTreeApi().then(data => {
        this.villageList = data
      })
    },
    handlerEdit() {
      //this.pram.roles = this.pram.roles.join(',')
      //console.log(this.pram);return;
      let pram=JSON.parse(JSON.stringify(this.pram));
      pram.villageId=pram.villageId[2]
      systemAdminApi.adminAdd(pram).then(data => {
        this.$message.success('更新管理员成功')
        this.$emit('hideEditDialog')
      })
    },
    rulesSelect(selectKeys) {
      this.pram.rules = selectKeys
    },
    handlerPwdInput(val) {
      if (!val) {
        this.rules.password = []
        this.rules.repwd = []
        return
      }
      this.rules.password = [
        { required: true, message: '请填管理员密码', trigger: ['blur', 'change'] },
        { min: 6, max: 20, message: '长度6-20个字符', trigger: ['blur', 'change'] }]
      this.rules.repwd = [{ required: true, message: '两次输入密码不一致', validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('两次输入密码不一致!'))
        } else if (value !== this.pram.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }, trigger: ['blur', 'change'] }]
    },
  }
}
</script>

<style scoped>

</style>
